import {
  Controller,
  Post,
  Get,
  Query,
  Body,
  Param,
  BadRequestException,
  CacheTTL,
} from '@nestjs/common'
import {
  ApiBearerAuth,
  ApiOperation,
  ApiTags,
  ApiQuery,
  ApiParam,
  ApiBody,
} from '@nestjs/swagger'
import {
  addAddressFromWechatDto,
  addressToCode,
  editAddressDto,
} from './dto/user-address.dto'
import { AddressService } from './address.service'
import to from 'await-to-js'
import axios from 'axios'
import { NoAuth } from 'src/utils/noAuth'
import { UserAddressEntity, UserEntity } from 'src/entities/user.entity'
import { CurrentUser } from 'src/common/decorator/user.decorator'
import { ProvinceEntity } from 'src/entities/province.entity'
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'

const md5 = require('js-md5')

@Controller('address')
@ApiTags('收货地址')
export class AddressController {
  constructor(
    private readonly AddressService: AddressService,
    @InjectRepository(ProvinceEntity)
    private readonly provinceRepository: Repository<ProvinceEntity>,
  ) {}

  @Post('/editAddress')
  @ApiOperation({
    summary: '创建编辑收货地址',
  })
  @ApiBody({
    type: editAddressDto,
  })
  @ApiBearerAuth()
  async editAddress(
    @Body() body: editAddressDto,
    @CurrentUser() user: UserEntity,
  ) {
    return await this.AddressService.editAddress(body, user)
  }

  @Post('/addAddressFromWechat')
  @ApiOperation({
    summary: '从微信收货地址导入',
  })
  @ApiBody({
    type: addAddressFromWechatDto,
  })
  @ApiBearerAuth()
  async addAddressFromWechat(
    @Body() body: addAddressFromWechatDto,
    @CurrentUser() user: UserEntity,
  ) {
    const province_code = (
      await this.provinceRepository.findOne({
        where: {
          name: body.province_name,
        },
      })
    ).code
    const city_code = (
      await this.provinceRepository.findOne({
        where: {
          name: body.city_name,
        },
      })
    ).code
    const country_code = (
      await this.provinceRepository.findOne({
        where: {
          name: body.country_name,
        },
      })
    ).code
    return await this.AddressService.editAddress(
      {
        ...body,
        isDefault: false,
        province_code,
        city_code,
        country_code,
      },
      user,
    )
  }

  @Get('/getAddress')
  @ApiOperation({
    summary: '获取用户收货地址列表',
  })
  @ApiBearerAuth()
  async getAddress(@CurrentUser() user: UserEntity) {
    return await this.AddressService.getAddress(user)
  }

  @Get('/changeDefaultAddress/:id')
  @ApiOperation({
    summary: '修改默认收货地址',
  })
  @ApiParam({
    name: '收货地址id',
    required: true,
  })
  @ApiBearerAuth()
  async changeDefaultAddress(
    @Param('id') id: number,
    @CurrentUser() user: UserEntity,
  ) {
    console.log('controoll change')
    return await this.AddressService.setDefaultAddress(id, user)
  }

  @Get('/changeAddressToCode')
  @ApiOperation({
    summary: '将地址转为code',
  })
  @ApiQuery({
    required: true,
    name: 'address',
  })
  @NoAuth()
  async changeAddressToCode(@Query() query: addressToCode) {
    const [err, res] = await to(
      axios.get('https://apis.map.qq.com/ws/geocoder/v1/', {
        params: {
          address: query.address,
          key: 'FGMBZ-U6YKQ-4CX5P-G6RFH-Q72VZ-ZCFSJ',
          sig: md5(
            `/ws/geocoder/v1/?address=${query.address}&key=FGMBZ-U6YKQ-4CX5P-G6RFH-Q72VZ-ZCFSJm3fyTayMkYlf4eLnyWoKSYxxyNA7E6yi`,
          ),
        },
      }),
    )
    if (err) return err
    return res.data.result
  }
}
